from django.shortcuts import render

# Create your views here.

import logging

# 1. 导入: 在需要使用的位置导入
# 2. 创建日志记录器: 导入后创建日志器才能使用
logger = logging.getLogger('django')

from django.views import View

import json, re
from django.http import JsonResponse

from django_redis import get_redis_connection
from .models import User

from django.contrib.auth import login, logout,authenticate  # login() 需要使用的方法,

from ihome_project.demo.demo import demo
from ihome_project.ihome.settings import PREFIX_URL,QINIU_BUCKET_DOMAIN
import os

# 用户登录接口
class LoginView(View):

    def post(self,request):
        # 提取参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')

        # 必要性校验
        if not all([mobile,password]):
            return JsonResponse({
                'errno':4101,
                'errmsg':'缺少必要性参数'
            })

        # 格式校验
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({
                'errno':4101,
                'errmsg':'手机号格式有误'
            })

        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$',password):
            return JsonResponse({
                'errno':4101,
                'errmsg':'密码格式错误'
            })

        # 业务数据处理
        # 使用自定义的全局认证后端实现登入验证
        user = authenticate(request,username=mobile,password=password)
        if user is None:
            return JsonResponse({
                'errno':4101,
                'errmsg':'手机号或者密码错误'
            })

        login(request, user)


        return JsonResponse({
            'errno':0,
            'errmsg':'登入成功'
        })

    # 判断是否登录接口
    def get(self,request):

        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'errno': 4101, 'errmsg': 'wei deng lu'})

        #业务数据处理
        userinfo = User.objects.get(pk=user.pk)

        return JsonResponse({
            'errno':0,
            'errmsg':'已登入',
            'data': {
                'name': userinfo.username,
                'user_id': userinfo.id
            }
        })

    # 退出登录接口
    def delete(self,request):

        logout(request)

        return JsonResponse({
            'errno':0,
            'errmsg':'ok'
        })


# 用户注册接口
class RegisterView(View):

    def post(self, request):

        # 1.获取参数
        data = json.loads(request.body.decode())

        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')
        # password2 = data.get('password2')

        # 2.校验参数
        if not all([mobile, password, phonecode]):  # 判断必须传入的参数
            return JsonResponse({'errno': 4101, 'errmsg': '缺少必要的参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):  # 判断手机号码的格式
            return JsonResponse({'errno': 4101, 'errmsg': '手机号码格式有问题'})

        if not re.match(r'^[a-zA-Z0-9-_]{8,20}$', password):  # 判断密码的格式
            return JsonResponse({'errno': 4101, 'errmsg': '密码格式错误'})

        # if password != password2:  # 判断两次密码是否一样
        #     return JsonResponse({'code': 400, 'errmsg': '两次密码输入不一样'})

        # 2.1短信验证码校验
        conn = get_redis_connection('verify_code')
        redis_sms_code = int(conn.get('sms_%s' % mobile))

        # 验证手机验证码
        if not redis_sms_code:
            return JsonResponse({'errno': 4101, 'errmsg': '短信验证码过期'})
        if int(phonecode) != redis_sms_code:
            return JsonResponse({'errno': 4101, 'errmsg': '手机验证码有误'})

        # 业务数据处理---新建用户
        try:
            user = User.objects.create_user(
                mobile=mobile,
                username=mobile,
                password=password
            )

        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4101, 'errmsg': '数据库新建失败'})

        # 状态保持
        login(request,user)

        # 4.返回响应
        response = JsonResponse({'errno': 0, 'errmsg': 'OK'})
        response.set_cookie('mobile', user.mobile, max_age=3600 * 24 * 14)
        return response



from ihome.utils.views import LoginRequiredJsonMixin


# 用户个人中接口
class UserInfoView(LoginRequiredJsonMixin, View):

    def get(self, request):

        # 获取登录用户
        user = request.user
        # 获取用户对象
        # user = User.objects.get(pk=user.id)

        # 拼接响应参数
        a = str(user.avatar)
        avatar_url = os.path.join(PREFIX_URL, QINIU_BUCKET_DOMAIN, a)
        data = {
            'user_id': user.id,
            'name': user.username,
            'mobile': user.mobile,
            'create_time': user.date_joined,
            'avatar': avatar_url
        }

        return JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': '0'
        })


# 上传头像
class UploadAvatarView(LoginRequiredJsonMixin,View):

    def post(self,request):

        # 获取文件,返回文件对象
        data_object = request.FILES.get('avatar')
        # 读取数据 ---二进制字节数据
        content = data_object.read()

        try:
            # 返回图片名字,默认自动生成图片名字
            return_key = demo(content)   # FhXkW17LfH9PVM3DoiTnAnlMGpaE
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,'errmsg':'上传头像失败'})

        user = request.user
        try:
            # 获取用户模型类对象
            user = User.objects.get(pk=user.id)
            # 修改字段，avatar
            user.avatar = return_key
            user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,'errmsg':'保存数据库失败'})

        # 拼接响应参数
        avatar_url = os.path.join(PREFIX_URL,QINIU_BUCKET_DOMAIN,return_key)

        return JsonResponse({
                            "data": {"avatar_url":avatar_url},
                            "errno": "0",
                            "errmsg": "头像上传成功"
                        })


# 修改用户名接口
class ChangUsernameView(LoginRequiredJsonMixin,View):

    def put(self,request):

        # 1.获取参数
        data = json.loads(request.body.decode())
        name = data.get('name')

        #2.校验参数
        if not name:
            return JsonResponse({'errno':400,'errmsg':'缺少必要参数'})
        if not re.match(r'^[a-zA-Z0-9-_]{5,20}$',name):  # 判断用户名的格式
            return JsonResponse({'code': 400, 'errmsg': '用户名格式有误'})

        # 3.业务数据处理---修改用户名并保存
        try:
            user=request.user
            # 修改用户名
            user.username = name
            user.save()
        except Exception as e:
            logger(e)
            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        # 4.构建响应
        return JsonResponse({"errno": "0","errmsg": "修改成功"})

# 用户实名认证接口
class RealNameView(LoginRequiredJsonMixin,View):

    def post(self,request):

        # 1. 获取参数
        data = json.loads(request.body.decode())

        real_name = data.get('real_name')
        id_card = data.get('id_card')

        # 2. 校验参数
        if not all([real_name,id_card]):
            return JsonResponse({'errno':4103,'errmsg':'缺少必要参数'})

        if re.match(r'^\u4e00-\u9fa5{1,5}$',real_name):
            return JsonResponse({'errno':4103,'errmsg':'参数错误1'})
        if re.match(r'/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/',id_card):
            return JsonResponse({'errno':4103,'errmsg':'参数错误22'})

        # 3. 业务数据处理---验证身份信息
        user = request.user
        # 真实姓名
        user.real_name = real_name
        # 身份证
        user.id_card = id_card
        user.save()

        # 4.构建响应
        return JsonResponse({
            'errno':0,
            'errmsg':'认证信息并保存'
        })


